<?php
namespace Portal\Common;

use \Portal\Model\Sms\Tpl as TplModel;
use \Portal\Model\Sms\Supplier as SupplierModel;

/**
 * 组件-短信
 */
class Iadminossms {

    /**
     * 发送短信
     * - HACK，异步支持
     * @param string|array $mobile 待发送的手机号，单个或多个
     * @param string $smsKey 内部的短信模板KEY
     * @param array $params 短信模板参数
     * @return boolean true|false，发送成功或失败
     */
    public function send($mobile, $smsKey, $params = array()) {
        // 手机号检测
        if (empty($mobile)) {
            return false;
        }

        $smsTpl = TplModel::model()->getData('sms_tpl_key = ?', $smsKey);
        if (empty($smsTpl)) {
            return false;
        }
        $smsSupplier = SupplierModel::model()->getData('id', $smsTpl['sms_supplier_id']);
        if (empty($smsSupplier)) {
            return false;
        }
        $smsSupplier['sms_supplier_config'] = json_decode($smsSupplier['sms_supplier_config'], true);

        // 通道类
        $channelClass = '\\Portal\\Domain\\Iadminossms\\' . ucfirst($smsSupplier['sms_supplier_type']);
        if (!class_exists($channelClass)) {
            return false;
        }

        // 发送短信
        $channelObj = new $channelClass();
        $context = array('smsTpl' => $smsTpl, 'smsSupplier' => $smsSupplier);
        $params = is_string($params) ? array($params) : $params;
        $sendRs = $channelObj->send($mobile, $params, $context);

        // 记录发送次数
        $totalTimes = is_array($mobile) ? count($mobile) : 1;
        $failTimes = 0;
        if (!$sendRs) {
            $failTimes = $totalTimes;
        }

        TplModel::model()->updateCounter('id = ' . $smsTpl['id'], array('sms_send_total_times' => $totalTimes, 'sms_send_fail_times' => $failTimes));
        SupplierModel::model()->updateCounter('id = ' . $smsSupplier['id'], array('sms_send_total_times' => $totalTimes, 'sms_send_fail_times' => $failTimes));

        return true;
    }
}
